package com.tkjt.pms.calc.formula.excel.builder.impl;

import java.util.List;

import org.springframework.stereotype.Component;

import com.tkjt.pms.calc.formula.common.FormulaConsts;
import com.tkjt.pms.calc.formula.common.FormulaVariableCells;
import com.tkjt.pms.calc.formula.excel.builder.DataKeyBuilder;
import com.tkjt.pms.calc.utils.EsCalcUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component(FormulaConsts.F_DATA_KEY_MI)
public class DataKeyMiBuilder implements DataKeyBuilder {

	@Override
	public FormulaVariableCells doBuilder(String formula, String variable, List<Double> variableValue, int lineNumber, String dataColumn, String indexYearMonth) {
		
		FormulaVariableCells formulaVariableCells = new FormulaVariableCells();
		
		StringBuilder excelFormulaBuilder = new StringBuilder(formula);

		//TEMP
		Integer dataColumnMi = null;
		if(!(dataColumn.startsWith("Q") || dataColumn.startsWith("q") || dataColumn.startsWith("mT")|| dataColumn.startsWith("mt"))) {
			dataColumnMi = EsCalcUtils.getDataColumnMi(dataColumn);
		} else {
			dataColumnMi = EsCalcUtils.getCalcMi(variable, indexYearMonth);
		}
		
		char startCol = 'B';
		String cellKey = String.valueOf(startCol) + lineNumber;
		Double oneCellColumnValue = null;
		if(null != dataColumnMi) {
			oneCellColumnValue = variableValue.get(dataColumnMi);
		}
		if(null == oneCellColumnValue) {
			formulaVariableCells.addCellValue(cellKey, null);
		} else {
			formulaVariableCells.addCellValue(cellKey, oneCellColumnValue.toString());
		}
		if(oneCellColumnValue < 0) {
			cellKey = "("+cellKey+")";
		}

		//替换掉公式中所有的配置变量：variable
		int start = 0;
		while(true) {
			int index = excelFormulaBuilder.indexOf(variable, start);
			if(index<0) {
				break;
			}
			if(index == 0){
				excelFormulaBuilder.replace(index, index+variable.length(), cellKey);
			}
			if(index > 0 && !EsCalcUtils.isVariableChar(excelFormulaBuilder.charAt(index-1))){
				excelFormulaBuilder.replace(index, index+variable.length(), cellKey);
			}
			start++;
		}
		
		formulaVariableCells.setCellFormula(excelFormulaBuilder.toString());
		
		log.debug(formulaVariableCells.getCellFormula());

		return formulaVariableCells;
	}

}
